package com.surprise.base.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.List;

/**
 * BeanUtilArrayToList.java
 * @author xuling
 * 2017年1月20日
 */
public class BeanUtilArrayToList extends BeanUtilBean {

    private static final BeanUtilArrayToList MY = new BeanUtilArrayToList();

    private BeanUtilArrayToList(){
    }

    public static final BeanUtilArrayToList getInstance() {
        return MY;
    }

    @Override
	public void copyProperty(Object destItem, String name, Object orgItem)
			throws IllegalAccessException, InvocationTargetException {
        Field field = null;
        try {
            field = destItem.getClass().getDeclaredField(name);
        } catch (NoSuchFieldException e) {
        	super.copyProperty(destItem, name, orgItem);
            return;
        }

        boolean isArrayToList = isArrayToListString(field, orgItem);

        if (isArrayToList == true) {
            String[] orgList = (String[]) orgItem;
            List<String> values = Arrays.asList(orgList);

            field.setAccessible(true);
            field.set(destItem, values);
        } else {
        	super.copyProperty(destItem, name, orgItem);
        }
	}

	@Override
	public void setProperty(Object destItem, String name, Object orgItem)
			throws IllegalAccessException, InvocationTargetException {

        Field field = null;
        try {
            field = destItem.getClass().getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            super.setProperty(destItem, name, orgItem);
            return;
        }

        boolean isArrayToList = isArrayToListString(field, orgItem);

        if (isArrayToList == true) {
            String[] orgList = (String[]) orgItem;
            List<String> values = Arrays.asList(orgList);

            field.setAccessible(true);
            field.set(destItem, values);
        } else {
        	super.setProperty(destItem, name, orgItem);
        }
	}

    public boolean isArrayToListString(Field field, Object orgItem) {
    	boolean ret = false;

        if (orgItem instanceof String[] && field.getType() == List.class) {
            ParameterizedType paramType = (ParameterizedType) field.getGenericType();
            Class paramCls = (Class) paramType.getActualTypeArguments()[0];
            if (paramCls == String.class) {
            	ret = true;
            }
        }

    	return ret;
    }
}
